import { defineEventHandler, getQuery } from 'h3';
import { type DriverSubsidyResponse } from './data'
import { mockDriverData, mockMileageData, subsidyStandards } from './data'


// 获取司机补贴报告数据
export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const { month, page = 1, pageSize = 20, sortBy, sortOrder } = query;

    // 验证月份参数
    if (!month || typeof month !== 'string') {
      return {
        success: false,
        data: null,
        message: '缺少统计月份参数',
      };
    }

    // 检查是否有该月份的数据
    const mileageData = mockMileageData[month as keyof typeof mockMileageData];
    if (!mileageData) {
      return {
        success: true,
        data: {
          list: [],
          total: 0,
          currentPage: Number.parseInt(page as string),
          pageSize: Number.parseInt(pageSize as string),
        },
        message: '当前月份暂无补贴统计数据',
      };
    }

    // 生成司机补贴数据
    const generateDriverSubsidyData = (): DriverSubsidyItem[] => {
      return mileageData.map((mileage) => {
        // 获取司机信息
        const driverInfo = mockDriverData.find(
          (driver) => driver.driverId === mileage.driverId,
        );

        if (!driverInfo) {
          throw new Error(`未找到司机ID ${mileage.driverId} 的信息`);
        }

        // 计算补贴总费用
        const totalSubsidy =
          Math.round(
            (mileage.provinceMileage * subsidyStandards.provinceSubsidyRate +
              mileage.outProvinceMileage *
                subsidyStandards.outProvinceSubsidyRate) *
              100,
          ) / 100;

        // 生成随机更新时间（当月内）
        const updateDate = new Date(`${month}-15`);
        updateDate.setHours(Math.floor(Math.random() * 24));
        updateDate.setMinutes(Math.floor(Math.random() * 60));
        updateDate.setSeconds(Math.floor(Math.random() * 60));
        const updateTime = updateDate
          .toISOString()
          .slice(0, 19)
          .replace('T', ' ');

        return {
          driverId: mileage.driverId,
          fullName: driverInfo.fullName,
          phoneNumber: driverInfo.phoneNumber,
          provinceMileage: mileage.provinceMileage,
          outProvinceMileage: mileage.outProvinceMileage,
          provinceSubsidyRate: subsidyStandards.provinceSubsidyRate,
          outProvinceSubsidyRate: subsidyStandards.outProvinceSubsidyRate,
          totalSubsidy,
          updateTime,
        };
      });
    };

    const driverSubsidyData = generateDriverSubsidyData();

    // 排序处理
    if (sortBy && sortOrder) {
      driverSubsidyData.sort((a, b) => {
        const aValue: any = a[sortBy as keyof DriverSubsidyItem];
        const bValue: any = b[sortBy as keyof DriverSubsidyItem];

        // 处理数字排序
        if (typeof aValue === 'number' && typeof bValue === 'number') {
          return sortOrder === 'asc' ? aValue - bValue : bValue - aValue;
        }

        // 处理字符串排序
        if (typeof aValue === 'string' && typeof bValue === 'string') {
          return sortOrder === 'asc'
            ? aValue.localeCompare(bValue, 'zh-CN')
            : bValue.localeCompare(aValue, 'zh-CN');
        }

        return 0;
      });
    }

    // 分页处理
    const currentPage = Number.parseInt(page as string);
    const currentPageSize = Number.parseInt(pageSize as string);
    const startIndex = (currentPage - 1) * currentPageSize;
    const endIndex = startIndex + currentPageSize;
    const paginatedData = driverSubsidyData.slice(startIndex, endIndex);

    const response: DriverSubsidyResponse = {
      list: paginatedData,
      total: driverSubsidyData.length,
      currentPage,
      pageSize: currentPageSize,
    };

    return {
      success: true,
      data: response,
      message: '获取成功',
    };
  } catch (error) {
    console.error('获取司机补贴统计数据失败:', error);
    return {
      success: false,
      data: null,
      message: '获取数据失败',
    };
  }
});
